//
//  SKUDetailController.m
//  Tang
//
//  Created by 352324497@qq.com on 15/12/9.
//  Copyright © 2015年 352324497@qq.com. All rights reserved.
//

#import "SKUDetailController.h"
#import "SKUDetailOneCell.h"
#import "UserInfoCell.h"
#import "SKUDetailThreeCell.h"
#import "SKUDetailFourCell.h"
#import "SKUDetailFourModel.h"
#import "SKUDetailOneModel.h"
#import "UserModel.h"
#import "PictureModel.h"
#import "CategoryListsModel.h"
#import "SDCycleScrollView.h"
#import "SKUDetailHeaderView.h"
#import "DIYButton.h"
#import "HomeDetailViewController.h"
#import "CommentsViewController.h"
#import "WebViewController.h"
#import "UMSocial.h"
@interface SKUDetailController ()<UITableViewDataSource, UITableViewDelegate, SDCycleScrollViewDelegate, SKUDetailFourDelegate, SKUDetailThreeDelegate>
{
    CGFloat  headerImageHeight;
}
@property (nonatomic, strong)NSMutableArray *oneArray;
@property (nonatomic, strong)NSMutableArray *twoArray;
@property (nonatomic, strong)NSMutableArray *threeArray;
@property (nonatomic, strong)NSMutableArray *fourArray;
@property (nonatomic, strong)NSMutableArray *photoArray;
@property (nonatomic, strong)NSMutableArray *picArray;
@property (nonatomic, strong)NSMutableArray *SCArray;
@property (nonatomic, strong)NSMutableArray *titleArray;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)SDCycleScrollView *headerImageView;
@property (nonatomic, strong)UILabel *titleLabel;
@property (nonatomic, strong)UIView *bottomView;
@property (nonatomic, copy)NSString *postStr1;
@property (nonatomic, copy)NSString *postStr2;

@end

@implementation SKUDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
    
    self.navigationController.navigationBar.translucent = YES;
      self.postStr1 = [NSString stringWithFormat:@"app_installtime=1449053241.284786&app_versions=5.0.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&comments_pagesize=10&id=%@&os_versions=9.1&screensize=640&track_deviceid=1AA9E26F-492E-48AC-8FC0-3FFA9007E29F&v=8",self.ID];
   // NSLog(@"0-0-0-%@", self.ID);
      self.postStr2 = [NSString stringWithFormat:@"app_installtime=1449053241.284786&app_versions=5.0.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&object_id=%@&os_versions=9.1&track_deviceid=1AA9E26F-492E-48AC-8FC0-3FFA9007E29F&type_id=2&v=8",self.ID];
    [self initView];
    
    if (self.photoArray.count != 0)
    {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.headerImageView.imageURLStringsGroup = self.photoArray;
        });
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [self findAllCommentsData:100];
}

#pragma mark - 设置页面
-(void)initView
{
    headerImageHeight = KWidth;
    // navigation title 设置
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    self.titleLabel.text = @"物品详情";
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = _titleLabel;
    self.titleLabel.alpha = 0;
    
    // 设置 tableView
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KWidth, KHeight - 60 * Kx6) style:(UITableViewStyleGrouped)];
    self.tableView.separatorStyle = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.contentInset = UIEdgeInsetsMake(headerImageHeight, 0, 0, 0);
    [self.tableView registerClass:[SKUDetailHeaderView class] forHeaderFooterViewReuseIdentifier:@"header"];
    [self.view addSubview:_tableView];
    
    // 设置 scrollView
    self.headerImageView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, -KWidth, KWidth, KWidth) imagesGroup:nil];
    self.headerImageView.autoScroll = YES;
    self.headerImageView.autoScrollTimeInterval = 2.0;
    self.headerImageView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    self.headerImageView.delegate = self;
    self.headerImageView.pageControlStyle = SDCycleScrollViewPageContolStyleClassic;
    self.headerImageView.placeholderImage = [UIImage imageNamed:@"PC"];
    // 是否无限循环
    self.headerImageView.infiniteLoop = NO;
    [self.tableView addSubview:_headerImageView];
    
    // 数据请求
    [self requestTitleDataWithPostString:_postStr1];
  
    [self requestDataWithPostString:_postStr2];
    if (self.photoArray.count != 0)
    {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.headerImageView.imageURLStringsGroup = self.photoArray;
        });
    }
    
    
    // 底部的 View
    self.bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, KHeight - 60 * Kx6, KWidth, 60 * Kx6)];
    self.bottomView.backgroundColor = [UIColor whiteColor];
    
    // 评论button
    DIYButton *commentButton = [DIYButton buttonWithType:(UIButtonTypeCustom)];
    commentButton.frame = CGRectMake(KWidth / 3 - 100 * Kx6, 10 * Kx6, 80 * Kx6, 30 * Kx6);
    commentButton.iconImageView.image = [UIImage imageNamed:@"comment"];
    commentButton.textLabel.text = @"评论";
    commentButton.textLabel.textColor = [UIColor lightGrayColor];
    commentButton.textLabel.font = [UIFont systemFontOfSize: 16 * Kx6];
        [commentButton addTarget:self action:@selector(commentAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.bottomView addSubview:commentButton];
    
    // 收藏 button
    DIYButton *likeButton = [DIYButton buttonWithType:(UIButtonTypeCustom)];
    likeButton.frame = CGRectMake(KWidth / 3 + KWidth / 3 - 100 * Kx6, 10 * Kx6, 80 * Kx6, 30 * Kx6);
    likeButton.iconImageView.image = [UIImage imageNamed:@"like"];
    likeButton.selectIconImageView.image = [UIImage imageNamed:@"islike"];
    likeButton.textLabel.text = @"喜欢";
    if ([[CoreDataMan shareIntance]findSkuWithId:_ID])
    {
        likeButton.selected = YES;
    }
    else
    {
        likeButton.selected = NO;
    }
    likeButton.textLabel.font = [UIFont systemFontOfSize:16 * Kx6];
    likeButton.textLabel.textColor = [UIColor lightGrayColor];
    [likeButton addTarget:self action:@selector(likeButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.bottomView addSubview:likeButton];
    
    // 购买 button
    DIYButton *buyButton = [DIYButton buttonWithType:(UIButtonTypeCustom)];
    buyButton.frame = CGRectMake(KWidth / 3 * 2 + KWidth / 3 - 100 * Kx6, 10 * Kx6, 80 * Kx6, 30 * Kx6);
    buyButton.layer.cornerRadius = 10 * Kx6;
    buyButton.backgroundColor = [UIColor orangeColor];
    buyButton.iconImageView.image = [UIImage imageNamed:@"buy"];
    buyButton.textLabel.text = @"购买";
    buyButton.textLabel.font = [UIFont systemFontOfSize:16 * Kx6];
    buyButton.textLabel.textColor = [UIColor whiteColor];
    [buyButton addTarget:self action:@selector(buyAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.bottomView addSubview:buyButton];
    
    [self.view addSubview:_bottomView];
    
    
    // 返回的 button
    UIButton *leftBtn=[UIButton buttonWithType:(UIButtonTypeCustom)];
    leftBtn.frame = CGRectMake(0, 0, 25, 25);
    [leftBtn setImage:[UIImage imageNamed:@"back"] forState:(UIControlStateNormal)];
    [leftBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftItem=[[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem=leftItem;
    
    // 分享的 button
    UIButton *rightBtn=[UIButton buttonWithType:(UIButtonTypeCustom)];
    rightBtn.frame = CGRectMake(0, 0, 25, 25);
    [rightBtn setImage:[UIImage imageNamed:@"share"] forState:(UIControlStateNormal)];
    [rightBtn addTarget:self action:@selector(share:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIBarButtonItem *rightItem=[[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem=rightItem;
}

- (void)findAllCommentsData:(NSInteger)limit
{
    BmobQuery *bquery = [BmobQuery queryWithClassName:[NSString stringWithFormat:@"Comments%@",_ID]];
    [bquery orderByDescending:@"createdAt"];
    bquery.limit = limit;
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error)
     {
         if (error)
         {
             NSLog(@"error:%@",error);

             
         }
         else
         {
             self.twoArray = [NSMutableArray array];
             for (BmobObject *obj in array)
             {
                 UserModel *model = [[UserModel alloc] init];
                 model.username = [obj objectForKey:@"userName"];
                 model.conent = [obj objectForKey:@"userComments"];
                 BmobQuery *bquery = [BmobQuery queryWithClassName:@"_User"];
                 model.time = [obj objectForKey:@"createdAt"];
                 dispatch_async(dispatch_get_main_queue(), ^
                 {
                     [bquery getObjectInBackgroundWithId:[obj objectForKey:@"author"] block:^(BmobObject *object, NSError *error)
                      {
                          [[NetworkState shareInstance] reachablityStatesWithDongHua:self];
                          BmobFile *file = [object objectForKey:@"headerImage"];
                          model.avatar = file.url;
                          [self.twoArray addObject:model];
                          
                          dispatch_async(dispatch_get_main_queue(), ^{
                              
                              [self.tableView reloadData];
                              [[NetworkState shareInstance] finshYYToVc:self];
                          }) ;
                          
                      }];
                     
                 });
             }
         }
         

     }];
    
}


#pragma mark - 标题数据请求
-(void)requestTitleDataWithPostString:(NSString *)postString
{
    [[NetworkState shareInstance]reachablityStatesWithDongHua:self];
    NSString *url = @"http://open3.bantangapp.com/product/newInfo";
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:10.0];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postData];
    
    [[[NSURLSession sharedSession]dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil)
        {
            NSLog(@"数据请求失败");
            UIAlertAction *OKaction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲, 网络好像不是很给力哦~~~" preferredStyle:(UIAlertControllerStyleAlert)];
            [alertView addAction:OKaction];
            [self presentViewController:alertView animated:YES completion:nil];
            [[NetworkState shareInstance] finshYYToVc:self];
            return ;
        }
        NSDictionary *Dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        NSDictionary *dataDic = Dic[@"data"];
        
        self.oneArray = [NSMutableArray array];
        self.photoArray = [NSMutableArray array];
        self.picArray = [NSMutableArray array];
        NSDictionary *product = dataDic[@"product"];
        for (NSDictionary *dic in product[@"pic"])
        {
            PictureModel *model = [[PictureModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.picArray addObject:model];
            [self.photoArray addObject:model.p];
        }
        if (self.photoArray.count != 0)
        {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.headerImageView.imageURLStringsGroup = self.photoArray;
            });
        }
        SKUDetailOneModel *model = [[SKUDetailOneModel alloc]init];
        [model setValuesForKeysWithDictionary:product];
        [self.oneArray addObject:model];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.headerImageView setNeedsLayout];
            [self.headerImageView setNeedsDisplay];
            [self.tableView reloadData];
            [[NetworkState shareInstance]finshYYToVc:self];
        });
    }]resume];
    
}

#pragma mark - 后两个 cell 的数据请求
-(void)requestDataWithPostString:(NSString *)postString
{
    NSString *url = @"http://open3.bantangapp.com/product/relation";
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:10.0];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postData];
    
    [[[NSURLSession sharedSession]dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil)
        {
            NSLog(@"数据请求失败");
            return ;
        }
        NSDictionary *Dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        NSDictionary *dataDic = Dic[@"data"];
        self.threeArray = [NSMutableArray array];
        self.fourArray = [NSMutableArray array];
        self.SCArray = [NSMutableArray array];
        self.titleArray = [NSMutableArray array];
        for (NSDictionary *dic in dataDic[@"product"])
        {
            SKUDetailFourModel *model = [[SKUDetailFourModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.fourArray addObject:model];
        }
        for (NSDictionary *dic in dataDic[@"topic"])
        {
            CategoryListsModel *model = [[CategoryListsModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.titleArray addObject:model.title];
            [self.SCArray addObject:model.pic];
            [self.threeArray addObject: model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }]resume];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    else if (section == 1)
    {
                if (self.twoArray.count != 0)
                {
                    return self.twoArray.count;
                }
                else
                {
                    return 0;
                }
        
    }
    else if (section == 2)
    {
        return 1;
    }
    else
    {
        return 1;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        if (self.oneArray.count != 0 && self.photoArray.count !=0)
        {
            SKUDetailOneModel *model = self.oneArray[indexPath.row];
            return [SKUDetailOneCell heightForCellWithModel:model];
        }
        return 0;
    }
    else if (indexPath.section == 1)
    {
                if (self.twoArray.count != 0)
                {
                    UserModel *model = self.twoArray[indexPath.row];
                    return [UserInfoCell heightForCellWithModel:model];
                }
                return 40 * Kx6;
        return 60 * Kx6;
    }
    else if (indexPath.section == 2)
    {
        if (self.threeArray.count != 0)
        {
            return  KWidth * 330 / 620 + 10 * Kx6;
        }
        return 0;
    }
    else
    {
        if (self.fourArray.count != 0)
        {
            return (242 * Kx6 + 10 * Kx6) * self.fourArray.count / 2;
        }
        return 0;
    }
}

#pragma mark - 设置表头
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 2)
    {
        if (self.titleArray.count != 0 && self.SCArray.count !=0)
        {
            SKUDetailHeaderView *headerView = [[SKUDetailHeaderView alloc]initWithReuseIdentifier:@"header"];
            headerView.titleLabel.backgroundColor = [UIColor whiteColor];
            headerView.titleLabel.text = @"----- 相关清单 -----";
            return headerView;
        }
        return nil;
    }
    else if (section == 3)
    {
        if (self.fourArray.count != 0)
        {
            SKUDetailHeaderView *headerView = [[SKUDetailHeaderView alloc]initWithReuseIdentifier:@"header"];
            headerView.titleLabel.backgroundColor = [UIColor whiteColor];
            headerView.titleLabel.text = @"----- 相关推荐 -----";
            return headerView;
        }
        return nil;
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 2)
    {
        if (self.titleArray.count != 0 && self.SCArray.count !=0)
        {
            return 50 * Kx6;
        }
        return 0.1;
    }
    else if (section == 3)
    {
        if (self.fourArray.count != 0)
        {
            return 50 * Kx6;
        }
        return 0.1;
    }
    return 0.1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
#pragma mark - 设置 cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0)
    {
        SKUDetailOneCell *cell = [tableView dequeueReusableCellWithIdentifier:@"oneCell"];
        if (cell == nil)
        {
            cell = [[SKUDetailOneCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"oneCell"];
        }
        if (self.oneArray.count != 0 && self.photoArray.count != 0)
        {
            SKUDetailOneModel *model = self.oneArray[indexPath.row];
            cell.model = model;
        }
        return cell;
    }
    else if (indexPath.section == 1)
    {
        UserInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"userCell"];
        if (cell == nil)
        {
            cell = [[UserInfoCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"userCell"];
        }
                if (self.twoArray.count != 0)
                {
                    UserModel *model = self.twoArray[indexPath.row];
                    cell.model = model;
                }
                else
                {
                    cell. detailTextLabel.text = @"暂时还没有评论...";
                }
        return cell;
    }
    else if (indexPath.section == 2)
    {
        SKUDetailThreeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"threeCell"];
        if (cell == nil)
        {
            cell = [[SKUDetailThreeCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"threeCell"];
        }
        if (self.SCArray.count != 0 && self.titleArray.count != 0)
        {
            [cell setPhotoWithArray:self.SCArray];
            [cell setTitleWithArray:self.titleArray];
        }
        cell.delegate = self;
        return cell;
    }
    else if (indexPath.section == 3)
    {
        SKUDetailFourCell * cell = [tableView dequeueReusableCellWithIdentifier:@"fourCell"];
        if (cell == nil)
        {
            cell = [[SKUDetailFourCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"fourCell"];
        }
        if (self.fourArray.count != 0)
        {
            [cell setItemsWithArray:self.fourArray];
        }
        cell.delegate = self;
        return cell;
    }
    
    return nil;
}

#pragma mark - 底部三个 button 的点击事件
-(void)commentAction:(DIYButton *)button
{
    BmobUser *bUser = [BmobUser getCurrentUser];
    if (bUser)
    {
    CommentsViewController *comments = [[CommentsViewController alloc]init];
    comments.indentierId = _ID;
   
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:comments];
    [self presentViewController:nav animated:NO completion:nil];
    }
        else
        {
            [CallTool alertActionWithTitle:@"提示" message:@"还没有登陆哦,请先登陆" other:@"取消"uiViewController:self];
        }

}

-(void)likeButtonAction:(DIYButton *)btn
{
    BmobUser *bUser = [BmobUser getCurrentUser];
    if (bUser)
    {
    
    btn.selected = !btn.selected;
  
    PictureModel *picModel = _picArray[0];
    SKUDetailOneModel *skuModel = _oneArray[0];
    
    if (btn.selected)
    {
        
        [[CoreDataMan shareIntance] addSku:[NSString stringWithFormat:@"%@",_ID] imageUrl:picModel.p title:skuModel.title type_id:nil width:picModel.w height:picModel.h];
    }
    else
    {
        [[CoreDataMan shareIntance] deleteSkuWithId:_ID];
    }
    }
    else
    {
        [CallTool alertActionWithTitle:@"提示" message:@"还没有登陆哦,请先登陆" other:@"取消"uiViewController:self];
    }

}

-(void)buyAction:(DIYButton *)button
{
    WebViewController *web = [[WebViewController alloc]init];
    SKUDetailOneModel *model = self.oneArray[0];
    web.url = model.url;
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController pushViewController:web animated:NO];
}
#pragma mark - 返回方法
-(void)backAction:(UIButton *)button
{
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController popViewControllerAnimated:NO];
}

#pragma mark - 分享
- (void)share:(UIButton *)button
{
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"5668e3bde0f55a90700038ed"
                                          shareText:@"推荐好物, 分享视频 https://itunes.apple.com/cn/app/%e7%b3%96%e5%a6%86/id1068451018?mt=8"
                                         shareImage:[UIImage imageNamed:@"Tango"]
                                    shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatTimeline, UMShareToWechatSession, UMShareToEmail, UMShareToSms,nil] delegate:nil];
}

//实现回调方法（可选）：
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}
#pragma mark - 手势方法
//-(void)tapAction:(UITapGestureRecognizer *)tap
//{
////    CommentsViewController *comments = [[CommentsViewController alloc]init];
////    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:comments];
////    [self presentViewController:nav animated:NO completion:nil];
//}
#pragma mark - 代理方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat yOffset = scrollView.contentOffset.y;
    CGFloat xOffeset = yOffset + headerImageHeight ;
    
    if (yOffset < - headerImageHeight)
    {
        CGRect rect = self.headerImageView.frame;
        rect.origin.y = yOffset;
        rect.size.height = - yOffset;
        rect.origin.x = xOffeset;
        rect.size.width = KWidth + fabs(xOffeset) * 2;
        self.headerImageView.frame = rect;

    }
    else
    {
        if  (yOffset <= 0)
            
        {
            CGFloat y = fabs(yOffset) ;
            self.tableView.contentInset = UIEdgeInsetsMake(y, 0, 0, 0);

        }
        
    }
    if (yOffset >= 0)
    {
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        self.tableView.height = KHeight - 60 * Kx6 - 64;
        self.bottomView.frame  = CGRectMake(0, KHeight - 60 * Kx6 - 64, KWidth, 60 * Kx6);
        self.navigationController.navigationBar.alpha = 1;
        self.navigationController.navigationBar.translucent = NO;
    }
    
    CGFloat alpha = (yOffset + headerImageHeight) / headerImageHeight;
    if (alpha > 1)
    {

        self.titleLabel.textColor = [[UIColor blackColor]colorWithAlphaComponent:alpha];
        self.tableView.height = KHeight - 60 * Kx6 - 64;
        self.bottomView.frame  = CGRectMake(0, KHeight - 60 * Kx6 - 64, KWidth, 60 * Kx6);
        
    }
    else
    {

        self.navigationController.navigationBar.translucent = YES;
        self.titleLabel.textColor = [UIColor clearColor];
        self.tableView.height = KHeight - 60 * Kx6;
        self.bottomView.frame = CGRectMake(0, KHeight - 60 * Kx6, KWidth, 60 * Kx6);
    }
    
    [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor whiteColor] colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault];
    self.titleLabel.alpha = alpha;
    alpha = fabs(alpha);
    alpha = fabs(1 - alpha);
    alpha = alpha < 0.2? 0 :alpha - 0.2;
}

- (UIImage *)imageWithColor:(UIColor *)color
{
    // 描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    
    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    
    return theImage;
}

#pragma mark - scrollView 的点击
-(void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    WebViewController *web = [[WebViewController alloc]init];
    SKUDetailOneModel *model = self.oneArray[0];
    web.url = model.url;
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController pushViewController:web animated:NO];
}
#pragma mark - 第二分区的点击
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1)
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
        UIAlertAction *report = [UIAlertAction actionWithTitle:@"举报" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [CallTool alertActionWithTitle:@"提示" message:@"举报成功" other:@"取消" uiViewController: self];
            
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
        [alert addAction:report];
        [alert addAction:cancel];
        [self presentViewController:alert animated:NO completion:nil];
    }

}
#pragma mark - 第三分区的代理
-(void)selectedPageWithIndex:(NSInteger)index
{
    UIImageView *temp = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    if (self.threeArray != 0)
    {
        CategoryListsModel *model = self.threeArray[index];
        HomeDetailViewController *homeDetailVc = [[HomeDetailViewController alloc]init];
        homeDetailVc.PinJieId = model.ID;
        [temp sd_setImageWithURL:[NSURL URLWithString:model.pic]];
        homeDetailVc.headerImage = temp.image;
        [self.navigationController pushViewController:homeDetailVc animated:YES];
    }
}
#pragma mark - 第四分区的代理
-(void)selectedCollectionWithIndexpath:(NSIndexPath *)indexPath
{
    self.ID = nil;
    if (self.fourArray.count != 0)
    {
        SKUDetailFourModel *model = self.fourArray[indexPath.row];
        self.ID = model.ID;
        self.postStr1 = nil;
        self.postStr2 = nil;
        self.postStr1 = [NSString stringWithFormat:@"app_installtime=1449053241.284786&app_versions=5.0.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&comments_pagesize=10&id=%@&os_versions=9.1&screensize=640&track_deviceid=1AA9E26F-492E-48AC-8FC0-3FFA9007E29F&v=8",self.ID];
        self.postStr2 = [NSString stringWithFormat:@"app_installtime=1449053241.284786&app_versions=5.0.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&object_id=%@&os_versions=9.1&track_deviceid=1AA9E26F-492E-48AC-8FC0-3FFA9007E29F&type_id=2&v=8",self.ID];
        [self initView];
        if (self.photoArray.count != 0)
        {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.headerImageView.imageURLStringsGroup = self.photoArray;
            });
        }
    }

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
